package com.liucxu.jiandanl.Widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.liucxu.jiandanl.Utils.DisplayUtils;

/**
 * 自定义的现实图片的控件
 * 图片现实的时候默认宽度充满
 * 长度同比例放大
 * 如果图片同比例放大之后的长度超过了屏幕的高度
 * 那么就只现实屏幕高度的1/3作为图片的高度
 * Created by liuchenxu on 2016/8/6.
 */
public class ShowMaxWidthImageView extends ImageView {

    private float mHeight = 0;

    public ShowMaxWidthImageView(Context context) {
        super(context);
    }

    public ShowMaxWidthImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ShowMaxWidthImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        if (drawable != null) {
            getHeight(drawable2Bitmap(drawable));
        }
        super.setImageDrawable(drawable);
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mHeight != 0) {
            float height = MeasureSpec.getSize(heightMeasureSpec);
            float width = MeasureSpec.getSize(widthMeasureSpec);
            float resultHeight = Math.max(height, mHeight);
            if(MeasureSpec.getMode(heightMeasureSpec)==MeasureSpec.EXACTLY){
                resultHeight=height;
            }
            else{
                if (resultHeight > DisplayUtils.GetDisplayHeight((Activity) getContext())) {
                    resultHeight = DisplayUtils.GetDisplayHeight((Activity) getContext()) / 3;
                }
            }
            setMeasuredDimension((int) width, (int) resultHeight);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        getHeight(bm);
        super.setImageBitmap(bm);
        requestLayout();
    }

    /**
     * @param drawable
     * @return
     */
    private Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable != null) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        } else {
            return null;
        }
    }

    /**
     * 得到缩放后的图片的高度
     *
     * @param bit
     */
    public void getHeight(Bitmap bit) {
        float width = bit.getWidth();
        float height = bit.getHeight();
        float Width = getWidth();
        float scale = Width / width;
        mHeight = height * scale;
    }
}
